<?php

namespace app\api\controller\app;

use app\admin\model\Banner;
use app\admin\model\City;
use app\admin\model\Org;
use app\admin\model\OrgIndexNotice;
use app\admin\model\OrgNotice;
use app\admin\model\Roomclean;
use app\admin\model\Shop;
use app\admin\model\Shopmno;
use app\admin\model\Shoporder;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoproombook;
use app\admin\model\Userallbalance;
use app\admin\model\Userbalance;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\api\service\VbillService;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Http;
use fast\Random;
use think\Config;
use think\Validate;

/**
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

    }

    public function getCityList()
    {
        $org_id = $this->request->param('org_id');
        $keyword = $this->request->param('keyword');
        $cityModel = new City();

        if($keyword != ""){
            $where['name'] = ['like', '%' . trim($keyword) . '%'];
        }
        $where['org_id'] = $org_id;
        $list = $cityModel->where($where)->order('weigh','desc')->select();
        $this->success('',$list);

    }

    public function getCityList2()
    {
        $keyword = $this->request->param('keyword');
        $cityModel = new City();

        $list = $cityModel->order('weigh','desc')->select();
        foreach ($list as $key=>$val){
            $list[$key]['title'] = $val['name'];
        }
        $hotList = $cityModel->where('is_hot',1)->order('weigh','desc')->select();
        foreach ($hotList as $key=>$val){
            $hotList[$key]['title'] = $val['name'];
        }
        $ret= array();
        $ret['all'] = $list;
        $ret['location'] = "长沙市";
        $ret['hot'] =$hotList;

        $this->success('',$ret);

    }

    public function notice(){
        $orgId = $this->request->param('orgId');
        $orgIndexNoticeModel = new OrgIndexNotice();
        $notice = $orgIndexNoticeModel->where('org_id',$orgId)->find();
        $this->success('',$notice);
    }

    public function getOrgShop(){

        $orgId = $this->request->param('orgId');
        $shopModel = new Shop();

        $shop = $shopModel->where('org_id',$orgId)->find();
        if(!$shop){
            $this->error("此机构下暂无店铺,请联系技术方");
        }
        $bannerModel = new Banner();
        $banner = $bannerModel->where('org_id',$orgId)->find();
        $bannerImg = cdnurl($banner['image'],true);
        $cover = explode(",",$shop['cover']);
        $list = array();
        foreach ($cover as $key=>$val){
            if($val != ""){
                $img = cdnurl($val,true);
                $list[] = $img;
            }
        }
        $shop['cover'] = $list;
        $shop['banner'] = $bannerImg;
        $this->success('',$shop);
    }

    public function getCity(){

      $lat =   $this->request->param('lat');
      $lng = $this->request->param('lng');
      $orgId = $this->request->param('orgId');

      $location = $lat.",".$lng;

      $url = "https://api.map.baidu.com/reverse_geocoding/v3/?ak=WSAp4TKKGV3RJ9gNoJWJexdhKnCKMcJ4&output=json&coordtype=wgs84ll&location=".$location;

      $result = Http::get($url);
      $result = json_decode($result,true);
      $ret = array();

      $orgNoticeModel = new OrgNotice();
      $notice = $orgNoticeModel->where('org_id',$orgId)->find();
      if($notice){
          $ret['notice'] = $notice['notice'];
      }else{
          $ret['notice'] = "";

      }
      if($result['status'] != 0){

          $cityModel = new City();
          $cityList = $cityModel->where('org_id',$orgId)->select();

          $ret['cityList'] = $cityList;
          $ret['cityName'] = "";

          $bannerModel = new Banner();
          $list = $bannerModel->where('org_id',$orgId)->select();
          $banners = array();
          foreach ($list as $key=>$val){
              $b = cdnurl($val['image'],true);
              $banners[]= $b;
          }
          $ret['banner'] = $banners;
          $this->success('',$ret);

      }else{

          $cityName = $result['result']['addressComponent']['city'];

          $cityModel = new City();
          $cityList = $cityModel->where('org_id',$orgId)->select();

          $ret['cityList'] = $cityList;
          $ret['cityName'] = $cityName;

          $bannerModel = new Banner();
          $list = $bannerModel->where('org_id',$orgId)->select();
          $banners = array();
          foreach ($list as $key=>$val){
              $b = cdnurl($val['image'],true);
              $banners[]= $b;
          }
          $ret['banner'] = $banners;

          $this->success('',$ret);

      }
    }

    public function getShopList(){


        $page = $this->request->param('page');
        $city = $this->request->param('city');
        $lat = $this->request->param('lat');
        $lng = $this->request->param('lng');
        $orgId =$this->request->param('orgId');

        $limit = 10;
        $offset = ($page - 1) * $limit;



        if($city != ''){

            $sql = "SELECT id,name,address,logo,lng,status,lat,tel,is_table from q_shop where  city = '".$city."' and status != -1 LIMIT $offset ,$limit";
        }else{

            $sql = "select * from(
SELECT id,name,address,logo,lng,lat,tel,is_table,status,
ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($lat*PI()/180-lat*PI()/180)/2),2)+COS($lat*PI()/180)*COS(lat*PI()/180)*POW(SIN(($lng*PI()/180-lng*PI()/180)/2),2)))*1000) AS distance
FROM q_shop where `status` !='-1') as tmp_table_name
order by distance LIMIT $offset ,$limit";
        }

        $user = $this->auth->getUser();
        if($user){
        }

        $shopModel = new Shop();
        $list = $shopModel->query($sql);


        foreach ($list as $key=>$val){
            $list[$key]['status_txt'] = $shopModel->getStatus($val['status']);
            $list[$key]['logo'] = cdnurl($val['logo'],true);
            if(isset($val['distance'])){
                $list[$key]['distance'] = round($val['distance']/1000,2)."km";

            }else{
                $list[$key]['distance'] = "";

            }
            $bookTime = $this->redis->get($val['id']);
            if($bookTime != null){
                $list[$key]['bookTime'] = time_ago(date("Y-m-d H:i:s",$bookTime))."有人预定";
            }else{
                if($val['status'] == 1 || $val['status'] == 2){
                    $list[$key]['bookTime'] =  rand(1,3)."小时前";
                }else{
                    $list[$key]['bookTime'] =  "";
                }
;
            }
        }

        $this->success('',$list);


    }


    public function getShopList2(){


        $page = $this->request->param('page');
        $city = $this->request->param('city');
        $lat = $this->request->param('lat');
        $lng = $this->request->param('lng');
        $orgId =$this->request->param('orgId');

        $limit = 10;
        $offset = ($page - 1) * $limit;



        if($city != ''){

            $sql = "SELECT id,name,address,logo,lng,status,lat,tel,is_table from q_shop where  city = '".$city."' and status != -1 LIMIT $offset ,$limit";
        }else{

            $sql = "select * from(
SELECT id,name,address,logo,lng,lat,tel,is_table,status,
ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($lat*PI()/180-lat*PI()/180)/2),2)+COS($lat*PI()/180)*COS(lat*PI()/180)*POW(SIN(($lng*PI()/180-lng*PI()/180)/2),2)))*1000) AS distance
FROM q_shop where `status` !='-1') as tmp_table_name
order by distance LIMIT $offset ,$limit";
        }

        $user = $this->auth->getUser();
        if($user){
        }

        $shopModel = new Shop();
        $list = $shopModel->query($sql);


        foreach ($list as $key=>$val){
            $list[$key]['status_txt'] = $shopModel->getStatus($val['status']);
            $list[$key]['logo'] = cdnurl($val['logo'],true);
            if(isset($val['distance'])){
                $list[$key]['distance'] = round($val['distance']/1000,2)."km";

            }else{
                $list[$key]['distance'] = "";

            }
            $bookTime = $this->redis->get($val['id']);
            if($bookTime != null){
                $list[$key]['bookTime'] = time_ago(date("Y-m-d H:i:s",$bookTime))."有人预定";
            }else{
                if($val['status'] == 1 || $val['status'] == 2){
                    $list[$key]['bookTime'] =  rand(1,3)."小时前";
                }else{
                    $list[$key]['bookTime'] =  "";
                }
            }
        }

        $this->success('',$list);


    }

    public function getShopListV2(){

        $page = $this->request->param('page');
        $city = $this->request->param('city');
        $lat = $this->request->param('lat');
        $lng = $this->request->param('lng');
        $orgId =$this->request->param('orgId');
        $type = $this->request->param('type');
        $keyword = $this->request->param('keyword');
        $limit = 10;
        $offset = ($page - 1) * $limit;

        $where = "";
        if($type != ""){
            if($type == 'qp'){
                $where = " and is_table=-1";
            }else{
                $where = " and is_table=1";

            }
        }

        if($keyword != ""){
            $where = " and name like'%".$keyword."%'";
        }

        if($city != ''){

            $sql = "SELECT id,name,address,logo,lng,status,lat,tel,is_table,temp_shop_id from q_shop where  city = '".$city."' and status != -1 $where LIMIT $offset ,$limit";
        }else{

            $sql = "select * from(
SELECT id,name,address,logo,lng,lat,tel,is_table,status,temp_shop_id,
ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($lat*PI()/180-lat*PI()/180)/2),2)+COS($lat*PI()/180)*COS(lat*PI()/180)*POW(SIN(($lng*PI()/180-lng*PI()/180)/2),2)))*1000) AS distance
FROM q_shop where `status` !='-1' $where) as tmp_table_name
order by distance LIMIT $offset ,$limit";
        }

        error_log("==sql==".$sql);

        $user = $this->auth->getUser();
        if($user){
            // error_log($user['id']."===========".$sql);
        }

        $shopModel = new Shop();
        $list = $shopModel->query($sql);


        foreach ($list as $key=>$val){
            $list[$key]['status_txt'] = $shopModel->getStatus($val['status']);
            $list[$key]['logo'] = cdnurl($val['logo'],true);
            if(isset($val['distance'])){
                $list[$key]['distance'] = round($val['distance']/1000,2)."km";

            }else{
                $list[$key]['distance'] = "";

            }
            if($val['temp_shop_id'] != -1){
                $bookTime = $this->redis->get($val['temp_shop_id']);

            }else{
                $bookTime = $this->redis->get($val['id']);

            }
            if($bookTime != null){
                $list[$key]['bookTime'] = time_ago(date("Y-m-d H:i:s",$bookTime))."有人预定";
            }else{
                $list[$key]['bookTime'] = "";
            }
        }
        $this->success('',$list);


    }

    public function getShopListV3(){

        $page = $this->request->param('page');
        $city = $this->request->param('city');
        $lat = $this->request->param('lat');
        $lng = $this->request->param('lng');
        $orgId =$this->request->param('orgId');
        $type = $this->request->param('type');
        $keyword = $this->request->param('keyword');
        $limit = 10;
        $offset = ($page - 1) * $limit;

        $where = "";
        if($type != ""){
            if($type == 'qp'){
                $where = " and is_table=-1";
            }else{
                $where = " and is_table=1";

            }
        }

        if($keyword != ""){
            $where = " and name like'%".$keyword."%'";
        }

        if($city != ''){

            $sql = "SELECT id,name,address,logo,lng,status,lat,tel,is_table,temp_shop_id from q_shop where  city = '".$city."' and status != -1 $where LIMIT $offset ,$limit";
        }else{

            $sql = "select * from(
SELECT id,name,address,logo,lng,lat,tel,is_table,status,temp_shop_id,
ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($lat*PI()/180-lat*PI()/180)/2),2)+COS($lat*PI()/180)*COS(lat*PI()/180)*POW(SIN(($lng*PI()/180-lng*PI()/180)/2),2)))*1000) AS distance
FROM q_shop where `status` !='-1' $where) as tmp_table_name
order by distance LIMIT $offset ,$limit";
        }

        error_log("==sql==".$sql);

        $user = $this->auth->getUser();
        if($user){
            // error_log($user['id']."===========".$sql);
        }

        $shopModel = new Shop();
        $list = $shopModel->query($sql);


        $shopRoomModel = new Shoproom();
        $shopTableModel = new \app\admin\model\Shoptable();
        foreach ($list as $key=>$val){

            $room_key = "room_count_".$val['id'];
            $table_key = "table_count_".$val['id'];

            $roomValue = $this->longRedis->get($room_key);
            if(!$roomValue){
                $roomValue = $shopRoomModel->where('shop_id',$val['id'])->where('status','free')->count('id');
            }

            $tableValue = $this->longRedis->get($table_key);
            if(!$tableValue){
                if($val['is_table'] == 1){
                    $tableValue =  $shopTableModel->where('shop_id',$val['id'])->where('status','free')->count('id');
                }else{
                    $tableValue=0;
                }
            }
            $list[$key]['room_free'] = $roomValue;
            $list[$key]['table_free'] = $tableValue;

            $list[$key]['status_txt'] = $shopModel->getStatus($val['status']);
            $list[$key]['logo'] = cdnurl($val['logo'],true);
            if(isset($val['distance'])){
                $list[$key]['distance'] = round($val['distance']/1000,2)."km";

            }else{
                $list[$key]['distance'] = "";

            }
            if($val['temp_shop_id'] != -1){
                $bookTime = $this->redis->get($val['temp_shop_id']);

            }else{
                $bookTime = $this->redis->get($val['id']);

            }
            if($bookTime != null){
                $list[$key]['bookTime'] = time_ago(date("Y-m-d H:i:s",$bookTime))."有人预定";
            }else{
                $list[$key]['bookTime'] = "";
            }
        }
        $this->success('',$list);


    }

    public function getShopListV4(){

        $page = $this->request->param('page');
        $city = $this->request->param('city');
        $lat = $this->request->param('lat');
        $lng = $this->request->param('lng');
        $orgId =$this->request->param('orgId');
        $type = $this->request->param('type');
        $keyword = $this->request->param('keyword');
        $limit = 10;
        $offset = ($page - 1) * $limit;

        $where = "";
        if($type != ""){
            if($type == 'qp'){
                $where = " and shop_type like '%棋牌%'";
            }else if($type == 'tq'){
                $where = " and shop_type like '%台球%'";
            }else if($type == 'ktv'){
                $where = " and is_ktv = 1";
            }
        }

        if($keyword != ""){
            $where = " and name like'%".$keyword."%'";
        }

        if($city != ''){

            $sql = "SELECT id,name,address,logo,lng,status,is_ktv,lat,tel,is_table,temp_shop_id,shop_type from q_shop where  city = '".$city."' and status != -1 $where LIMIT $offset ,$limit";
        }else{

            $sql = "select * from(
SELECT id,name,address,logo,lng,is_ktv,lat,tel,is_table,status,temp_shop_id,shop_type,
ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($lat*PI()/180-lat*PI()/180)/2),2)+COS($lat*PI()/180)*COS(lat*PI()/180)*POW(SIN(($lng*PI()/180-lng*PI()/180)/2),2)))*1000) AS distance
FROM q_shop where `status` !='-1' $where) as tmp_table_name
order by distance LIMIT $offset ,$limit";
        }

        error_log("==sql==".$sql);

        $user = $this->auth->getUser();
        if($user){
            // error_log($user['id']."===========".$sql);
        }

        $shopModel = new Shop();
        $list = $shopModel->query($sql);


        $shopRoomModel = new Shoproom();
        $shopTableModel = new \app\admin\model\Shoptable();
        foreach ($list as $key=>$val){

            $room_key = "room_count_".$val['id'];
            $table_key = "table_count_".$val['id'];

            $roomValue = $this->longRedis->get($room_key);
            if(!$roomValue){
                $roomValue = $shopRoomModel->where('shop_id',$val['id'])->where('status','free')->count('id');
            }
            $list[$key]['qp'] = -1;
            $list[$key]['tq'] = -1;

            if($val['shop_type'] == '棋牌'){
                $list[$key]['qp'] = 1;
            }else if($val['shop_type'] == '台球'){
                $list[$key]['tq'] = 1;
            }else if($val['shop_type'] == '棋牌台球' ||  $val['shop_type'] == '台球棋牌'){
                $list[$key]['tq'] = 1;
                $list[$key]['qp'] = 1;
            }

            $tableValue = $this->longRedis->get($table_key);
            if(!$tableValue){
                if($val['is_table'] == 1){
                    $tableValue =  $shopTableModel->where('shop_id',$val['id'])->where('status','free')->count('id');
                }else{
                    $tableValue=0;
                }
            }
            $list[$key]['room_free'] = $roomValue;
            $list[$key]['table_free'] = $tableValue;

            $list[$key]['status_txt'] = $shopModel->getStatus($val['status']);
            $list[$key]['logo'] = cdnurl($val['logo'],true);
            if(isset($val['distance'])){
                $list[$key]['distance'] = round($val['distance']/1000,2)."km";

            }else{
                $list[$key]['distance'] = "";

            }
            if($val['temp_shop_id'] != -1){
                $bookTime = $this->redis->get($val['temp_shop_id']);

            }else{
                $bookTime = $this->redis->get($val['id']);

            }
            if($bookTime != null){
                $list[$key]['bookTime'] = time_ago(date("Y-m-d H:i:s",$bookTime))."有人预定";
            }else{
                $list[$key]['bookTime'] = "";
            }
        }
        $this->success('',$list);


    }


    public function search(){

        $page = $this->request->param('page');
        $lat = $this->request->param('lat');
        $lng = $this->request->param('lng');
        $keyword = $this->request->param('keyword');
        $orgId = $this->request->param('orgId');

        $limit = 10;
        $offset = ($page - 1) * $limit;


        $where = " where org_id=".$orgId;
        if($keyword != ''){
          $where .=  " and name like '%".$keyword."%'";
        }

        if($lat == ''){
            $sql = "SELECT id,name,address,logo,lng,lat,tel,is_table from q_shop $where  LIMIT $offset ,$limit";

        }else{
            $sql = "select * from(
SELECT id,name,address,logo,lng,lat,tel,is_table,
ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($lat*PI()/180-lat*PI()/180)/2),2)+COS($lat*PI()/180)*COS(lat*PI()/180)*POW(SIN(($lng*PI()/180-lng*PI()/180)/2),2)))*1000) AS distance
FROM q_shop  $where LIMIT $offset ,$limit)  as tmp_table_name
order by distance";
        }


        $shopModel = new Shop();
        $list = $shopModel->query($sql);


        foreach ($list as $key=>$val){
            $list[$key]['logo'] = cdnurl($val['logo'],true);
            if(isset($val['distance'])){
                $list[$key]['distance'] = round($val['distance']/1000,2)."km";

            }else{
                $list[$key]['distance'] = "";
            }
            $bookTime = $this->redis->get($val['id']);
            if($bookTime != null){
                $bookTime = date("Y-m-d H:i:s",$bookTime);  
                $list[$key]['bookTime'] = time_ago($bookTime)."有人预定";
            }else{
                $list[$key]['bookTime'] = "";
            }
        }
        $this->success('',$list);


    }

    public function testRefund(){


        $order_no = $this->request->param('order_no');
        $amount = $this->request->param('amount');
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no',$order_no)->find();

        if($amount == 0){
            $this->error("退款金额不能为0");
        }
        $user = $this->auth->getUser();
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id',$order['shop_id'])->find();

        $backBalanceAmount = 0;
        if($order['balance']>=$amount){
            $refundAmount = 0;
            $backBalanceAmount = $amount;
        }else{
            $refundAmount = $amount-$order['balance'];
            $backBalanceAmount = $order['balance'];
        }

        if($order['pay_amount'] >0 && $refundAmount>0){


            $refundOrder_no = getOrderSn();

            $orgModel = new Org();
            $org = $orgModel->where('id',$order['org_id'])->find();

            $shopMnoModel = new Shopmno();
            $shopMno = $shopMnoModel->where('shop_id',$order['shop_id'])->find();
            $mno = $org['mno'];
            if($shopMno && $shopMno['ratio'] == 100){
                $mno = $shopMno['mno'];
            }
            $req = array();
            $req['mno']= $mno;
            $req['ordNo']= $refundOrder_no;
            $req['origOrderNo']= $order['order_no'];
            $req['amt']=$refundAmount;



            $vbillService = new VbillService();
            $ret = $vbillService->refund($req);
            error_log("====refund===".$ret);
            $result = json_decode($ret,true);
            if($result['respData']['bizCode'] != "0000"){
                $this->error($result['respData']['bizMsg'],$req);
            }
            $shopOrderModel->where('id',$order['id'])->update(['status'=>'refund','refund_order_no'=>$refundOrder_no]);
        }else{
            $shopOrderModel->where('id',$order['id'])->update(['status'=>'refund']);
        }
        //退余额
        if($order['balance'] >0){
            $userBalanceModel = new Userbalance();
            $balanceDb = $userBalanceModel->where('user_id',$order['user_id'])->where('order_id',$order['id'])->where('type','out')->find();
            $userBalanceModel->insert(['user_id'=>$balanceDb['user_id'],'type'=>'in','amount'=>$backBalanceAmount,'mark'=>'订单退款','create_time'=>time(),
                'shop_id'=>$balanceDb['shop_id'],'order_id'=>$balanceDb['order_id'],'b_type'=>'refund']);
        }
        //退商家分润 ，代理商分润
        if($order['pay_amount'] >0){
            $shopOrderProfitModel =new Shoporderprofit();
            $shopOrderProfitModel->where('order_id',$order['id'])->where('user_id',$shop['user_id'])->delete();

            $userOrderProfitModel = new Userorderprofit();
            $userOrderProfitModel->where('user_id',$shop['agent_id'])->where('order_id',$order['id'])->delete();
        }

        //团购券
        if($order['tuan_id'] != -1){
            $userTuanModel = new Usertuan();
            $userTuanModel->where('order_id',$order['id'])->update(['status'=>'unuse']);
        }

        //恢复预定
        $roomBookOrderModel = new Shoproombook();
        $roomBookOrderModel->where('order_id',$order['id'])->delete();

        $cleanRoomModel = new Roomclean();
        $cleanRoomModel->where('order_id',$order['id'])->delete();

        $this->success('成功');
    }

    public function testLock()
    {
        $key  = "room_1";
        $cache = $this->redis->get($key);
        $this->success('',$cache);

    }

    public function testFz()
    {

        $amount = $this->request->param('amount');
        $userAllbalanceModel = new Userallbalance();
        $list = $userAllbalanceModel->cacBalance(7368,$amount);
        $this->success('',$list);
    }








}
